package com.sinbad.fileupload.util;

import com.sinbad.common.core.util.DateUtils;
import com.sinbad.common.core.util.IdUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: sinbad
 * @time: 2021/10/26
 * @description： 文件上传工具类
 */
public class FileUploadUtil {


    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        String fileName;
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + "/" + IdUtil.fastUUID() + "." + extension;
        return fileName;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}
